package com.tulele.vtool.handler;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.tulele.vtool.model.BargainParticipantsInfo;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.model.UserBargainActivityInfo;
import com.tulele.vtool.model.UserInfo;
import com.tulele.vtool.model.reqEntity.GetBargainActParticipantsInfoReqBean;
import com.tulele.vtool.model.reqEntity.ParticipateBargainActivityReqBean;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.IUserBargainActivityService;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.service.SysGzhService;
import com.tulele.vtool.utils.AliImgUtil;
import com.tulele.vtool.utils.SysConstant;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import com.tulele.vtool.wechat.service.WeixinServiceNew;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@RestController
public class UserBargainActivityHandler {

    @Autowired
    private IUserBargainActivityService userBargainActivityService;

//    @Autowired
//    private WeixinService weixinService;

//    @Autowired
//    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private IUserInfoService userInfoService;

    @PostMapping(value = "/participateBargainActivity", produces="application/json;charset=UTF-8")
    public RespData participateBargainActivity(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody ParticipateBargainActivityReqBean participateBargainActivityReqBean) {

        int bargainActId = Optional.ofNullable(participateBargainActivityReqBean.getBargainActId()).orElse(0);
        int actInitUserId = Optional.ofNullable(participateBargainActivityReqBean.getBargainActInitUserId()).orElse(0);
        int participateUserId = Integer.parseInt(userId);

        //如果没有bargainActId，则参与者必须是用户自己，否则返回参数异常
        if (bargainActId == 0 && participateUserId != actInitUserId) {

            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;

        }

        //参与类型 1-用户自己参与自己的活动 2-用户参与别人的活动
        int participateType = 1;
        if (actInitUserId != participateUserId) {

            participateType = 2;

        }

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);

        resultMap.put("participateType", participateType);

        if (participateType == 1) {

            //如果是用户自己参与自己的活动，并且活动ID大于0，说明已经参与了活动，此时返回相关活动信息
            if (bargainActId > 0) {

                resultMap.put("bargainActId", bargainActId);

            } else {

                //否则认为是用户头一次自己参加活动
                bargainActId = userBargainActivityService.participateBargainActivity(actInitUserId, participateUserId, bargainActId, SysConstant.BARGAIN_AMOUNT);

                resultMap.put("bargainActId", bargainActId);
            }

            //获取用户发起的活动信息
            UserBargainActivityInfo userBargainActivityInfo = userBargainActivityService.getUserBargainActInfo(bargainActId);

            resultMap.put("bargainActStartTime", userBargainActivityInfo.getCreateTime());
            resultMap.put("effectivePeriod", userBargainActivityInfo.getEffectivePeriod());
            resultMap.put("participantsTotalCount", Optional.ofNullable(userBargainActivityInfo.getParticipantsTotalCount()).orElse(0));
            resultMap.put("bargainTotalAmount", Optional.ofNullable(userBargainActivityInfo.getBargainTotalAmount()).orElse(0));

            //获取用户活动参与信息
            int bargainAmount = Optional.ofNullable(userBargainActivityService.getUserBargainAmountByActId(participateUserId, bargainActId)).orElse(0);
            resultMap.put("bargainAmount", bargainAmount);

        } else {

            //先查询当前用户是否已经参与了该活动
            int participateActStatus = userBargainActivityService.getUserParticipateActStatus(participateUserId, bargainActId);
            if (participateActStatus > 0) {

                int bargainAmount = Optional.ofNullable(userBargainActivityService.getUserBargainAmountByActId(participateUserId, bargainActId)).orElse(0);
                resultMap.put("bargainAmount", bargainAmount);

            } else {

                //用户参加砍价活动
                userBargainActivityService.participateBargainActivity(actInitUserId, participateUserId, bargainActId, SysConstant.BARGAIN_AMOUNT);

                resultMap.put("bargainAmount", SysConstant.BARGAIN_AMOUNT);
            }


            resultMap.put("bargainActId", bargainActId);

            //获取用户昵称
            UserInfo actInitUser = userInfoService.getUserBaseInfo(actInitUserId);
            resultMap.put("actInitUserNickName", actInitUser.getNickName());

            int concernStatus = Optional.ofNullable(actInitUser.getConcernStatus()).orElse(0);
            resultMap.put("concernStatus", concernStatus);

            if (concernStatus == 0) {

                try {

//                    WeixinServiceDL weixinService= objectFactory.getObject();
//                    weixinService.reSetConfigStorage(springProfilesActive);
                    PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
                    //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
                    WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);
                    WxMpQrCodeTicket ticket = weixinService.getQrcodeService().qrCodeCreateTmpTicket(actInitUserId, 2592000);
                    File qrCodePictureFile = weixinService.getQrcodeService().qrCodePicture(ticket);

                    String imgName = UUID.randomUUID().toString() + ".jpg";

                    AliImgUtil.uploadWechatQrCodeImg(userId, imgName, qrCodePictureFile);

                    String userQrCodeUrl = SysConstant.USER_PARAM_QRCODE_IMG_ACCESS_PREFIX + SysConstant.WX_PN_QRCODE_IMG_FOLDER_PATH + userId + "/" + imgName;

                    resultMap.put("userQrCodeUrl", userQrCodeUrl);

                } catch (WxErrorException e) {
                    e.printStackTrace();
                }

            }


        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;

    }

    @PostMapping(value = "/getBargainActInfo", produces="application/json;charset=UTF-8")
    public RespData participateBargainActivity(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestParam("bargainActId") Integer bargainActId) {

        if (bargainActId == null) {

            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;

        }

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(5);
        resultMap.put("bargainActId", bargainActId);

        UserBargainActivityInfo userBargainActivityInfo = userBargainActivityService.getUserBargainActInfo(bargainActId);

        int actStatus = Optional.ofNullable(userBargainActivityInfo.getActStatus()).orElse(0);
        if (actStatus == 0) {

            //获取用户信息
            UserInfo actInitUser = userInfoService.getUserBaseInfo(userBargainActivityInfo.getUserId());

            int concernStatus = Optional.ofNullable(actInitUser.getConcernStatus()).orElse(0);
            resultMap.put("concernStatus", concernStatus);
            resultMap.put("bargainActInitUserId", actInitUser.getUserId());

            if (concernStatus == 0) {

                try {

//                    WeixinServiceDL weixinService= objectFactory.getObject();
//                    weixinService.reSetConfigStorage(springProfilesActive);
                    PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
                    //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
                    WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);
                    WxMpQrCodeTicket ticket = weixinService.getQrcodeService().qrCodeCreateTmpTicket(actInitUser.getUserId(), 2592000);
                    File qrCodePictureFile = weixinService.getQrcodeService().qrCodePicture(ticket);

                    String imgName = UUID.randomUUID().toString() + ".jpg";

                    AliImgUtil.uploadWechatQrCodeImg(userId, imgName, qrCodePictureFile);

                    String userQrCodeUrl = SysConstant.USER_PARAM_QRCODE_IMG_ACCESS_PREFIX + SysConstant.WX_PN_QRCODE_IMG_FOLDER_PATH + userId + "/" + imgName;

                    resultMap.put("userQrCodeUrl", userQrCodeUrl);

                } catch (WxErrorException e) {
                    e.printStackTrace();
                }

            }

        } else {

            //获取最新3条砍价记录
            List<BargainParticipantsInfo> bargainParticipantsInfoList = userBargainActivityService.getSpecialSizeBargainParticipantsInfoByActId(bargainActId);

            resultMap.put("bargainActParticipantsInfo", bargainParticipantsInfoList);

        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getBargainActParticipantsInfo", produces="application/json;charset=UTF-8")
    public RespData getBargainActParticipantsInfo(@RequestHeader("userId") String userId, @RequestBody GetBargainActParticipantsInfoReqBean getBargainActParticipantsInfoReqBean) {

        if (getBargainActParticipantsInfoReqBean == null || getBargainActParticipantsInfoReqBean.getBargainActId() == null) {

            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;

        }

        Map<String, Object> queryMap = Maps.newHashMap();

        Integer pageNum = getBargainActParticipantsInfoReqBean.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = 1;
        }

        Integer pageSize = getBargainActParticipantsInfoReqBean.getPageSize();
        if (pageSize == null || pageNum.intValue() <= 0) {
            pageSize = 10;
        }

        PageInfo<BargainParticipantsInfo> participantsInfoPageInfo = userBargainActivityService.getBargainParticipantsInfoByActId(getBargainActParticipantsInfoReqBean.getBargainActId(), pageNum, pageSize);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);

        long count = participantsInfoPageInfo.getTotal();
        resultMap.put("count", count);
        resultMap.put("items", participantsInfoPageInfo.getList());
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }
}
